<template>
  <el-dialog
    :model-value="props.loadSchemeFormVisible"
    title="选择方案"
    width="80%"
    :before-close="handleClose"
  >
    <div class="scheme-form">
      <div class="scheme-form-item fangAn">
        <h3>方案列表：</h3>
        <el-table
          @cell-contextmenu="cellContextMenu"
          @cell-click="cellMouseLeave"
          :data="tableData"
          @row-click="rowClick"
          style="width: 100%"
          highlight-current-row
        >
          <el-table-column
            type="index"
            label="序号"
            width="80"
          ></el-table-column>
          <el-table-column
            prop="planName"
            label="名称"
            width="150"
          ></el-table-column>
          <el-table-column
            prop="createTime"
            width="200"
            label="时间"
          ></el-table-column>
          <el-table-column
            width="150"
            prop="remark"
            label="备注"
          ></el-table-column>
        </el-table>
      </div>
      <div class="tb-position">
        <!-- 台区显示内容 -->
        <div class="station-area">
          <div class="station-area-item" v-for="item in stationData">
            <p class="item1">
              <span v-if="item.state">
                {{ item.pname }}
              </span>
              <span v-else>
                {{ item.label }}
              </span>
            </p>
            <p class="item3">
              <img v-if="item.state" src="@/assets/images/station-area1.png" />
              <img v-else src="@/assets/images/station-area2.png" />
            </p>
            <p class="item2">{{ item.name }}</p>
          </div>
        </div>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">返回</el-button>
        <el-button type="primary" @click="handle(ruleFormRef)">
          确定
        </el-button>
      </span>
    </template>
    <!-- 右键删除内容 -->
    <div id="tbMenu1" class="tbMenuDiv">
      <ul class="tbMenuUl">
        <li
          v-for="(item, index) in tbMenus"
          :key="index"
          @click.stop="infoClickTb(item.type)"
        >
          {{ item.name }}
        </li>
      </ul>
    </div>
  </el-dialog>
</template>
<script setup>
import { ref, reactive, onUpdated } from "vue";
import { useAppStore, paramsDataStore } from "@/stores";
import { ElMessage, ElMessageBox } from "element-plus";
import { storeToRefs } from "pinia";
import {
  meterPositionPlanList,
  meterPositionPlanRemove,
  meterPositionList,
  meterPositionListTree,
} from "@/api/app.js";

const useApp = useAppStore();
let {
  organStructure,
  monthMeterReading,
  currentAccountingData,
  receivedData,
  currentPlanId,
  tableFault,
  tableHeader,
  tableStudent,
  calculationData,
  tableFaultSetting,
} = storeToRefs(useApp);
const paramsData = paramsDataStore();
let { stationData, newStationArea, stationArea } = storeToRefs(paramsData);

const emit = defineEmits(["is-show"]);

const props = defineProps({
  loadSchemeFormVisible: Boolean,
});
const tableData = ref([]);
const currentData = ref([]);
const currentDataList = ref([]);
const newData = ref([]);
const twfForm = reactive({
  ttype: [],
  vlf: [],
  vps: "U_ABC",
  clf: [],
  cps: "I_ABC",
});

const meterMalForm1 = reactive({
  fault1: [],
  fault2: [],
  fault3: "9",
  fault4: "13",
  fault5: "16",
  fault6: "19",
  fault7: "22",
  fault8: "25",
  fault9: "28",
  fault10: "31",
  fault11: "1",
  fault12: "6",
});
const meterMalForm2 = reactive({
  fault1: [],
  fault2: [],
  fault3: [],
  fault4: [],
  fault5: [],
  fault6: [],
  fault7: [],
  fault8: [],
  fault9: [],
  fault10: [],
  fault11: [],
});
const form = reactive({
  name: "",
  remark: "",
});
const rules = reactive({
  name: [{ required: true, message: "请输入方案名称", trigger: "blur" }],
});
const tbMenus = ref([
  {
    id: 2,
    name: "删除",
    type: 2,
  },
]);

//初始化列表
onUpdated(() => {
  getList();
});
const handleClose = () => {
  emit("is-show");
};
//点击确定
const handle = async () => {
  let parm = {};
  parm = {
    planId: currentData.value.id,
  };
  monthMeterReading.value = [];
  receivedData.value = [];
  calculationData.value = [];
  currentAccountingData.value = [];
  await meterPositionListTree(parm)
    .then((res) => {
      stationArea.value = JSON.parse(JSON.stringify(stationData.value));
      organStructure.value[0].children = JSON.parse(JSON.stringify(res.data));
      // console.log("organStructure.value", res.data, organStructure.value);
      currentPlanId.value = currentData.value.id;
      matchedTableData(res.data); //匹配树状结构数据
      matchedTableHeader(); //匹配树状结构数据头部信息
      emit("is-show");
    })
    .catch(() => {
      emit("is-show");
    });
};
const matchedTableData = (data) => {
  tableStudent.value = [];
  data.forEach((item) => {
    currentDataList.value.forEach((item1) => {
      if (item.id === item1.id) {
        item.children = item1.children;
      }
    });
    if (item.type === 1 || item.type === 5) {
      let flag = false;
      item.children.forEach((item1) => {
        if (item1.type === 7) {
          flag = true;
        }
        if (item1.type === 3) {
          flag = true;
        }
      });
      if (flag) {
        tableStudent.value.push(item);
      }
    }
    if (item.type === 8) {
      tableStudent.value.push(item);
    }
  });
  tableFault.value = JSON.parse(JSON.stringify(data));
  //tableStudent.value = JSON.parse(JSON.stringify(tableFault.value));
};
//行点击事件
const rowClick = async (row, column, event) => {
  currentData.value = row;
  let parm = {
    planId: row.id,
  };
  await meterPositionList(parm)
    .then((res) => {
      newData.value = res.data;
      matchedData(res.data);
      matchedMenuChild(res.data);
    })
    .catch(() => {});
};
//匹配显示数据
const matchedData = (data) => {
  stationData.value.forEach((item) => {
    item.state = 0;
    item.name = "";
    item.pname = "";
    item.checked = false;
    item.disabled = false;
    data.forEach((item1) => {
      if (item1.position === Number(item.value)) {
        item.state = 1;
        item.name = item1.name;
        item.pname = item1.pname;
        item.checked = true;
        item.disabled = true;
      }
      tableFaultSetting.value[item1.position + "b1"] = meterMalForm1;
      tableFaultSetting.value[item1.position + "b2"] = meterMalForm2;
      tableFaultSetting.value[item1.position + "a"] = twfForm;
    });
  });
  newStationArea.value = JSON.parse(JSON.stringify(stationData.value));
  // console.log(stationData.value);
};
//匹配台区数据 子菜单追加
const matchedMenuChild = (data) => {
  currentDataList.value = data.filter((item) => item.type === 1);
  currentDataList.value.forEach((item) => {
    item.children = [];
    data.forEach((item1) => {
      if (item1.type != 4 && item.id === item1.pid) {
        item.children.push(item1);
      }
      if (item1.type == 4 && item.pname === item1.pname) {
        item.children.push(item1);
      }
    });
  });
};
//匹配表格头部信息
const matchedTableHeader = () => {
  let arr = [3, 4, 7, 8];
  tableHeader.value = [];
  newData.value.forEach((item) => {
    if (arr.includes(item.type)) {
      tableHeader.value.push(item); //动态追加组织树状结构 表格头部
    }
  });
};
const getList = async () => {
  await meterPositionPlanList()
    .then((res) => {
      tableData.value = res.data;
      // console.log(tableData.value);
    })
    .catch(() => {
      // console.log(res);
    });
};
//右键事件
const cellContextMenu = (row, column, cell, event) => {
  currentData.value = row;
  let menu = document.querySelector("#tbMenu1");
  //阻止元素发生默认的行为
  event.preventDefault();
  // 根据事件对象中鼠标点击的位置，进行定位
  // console.log(event.clientX, event.clientY);
  menu.style.left = event.clientX - 190 + "px";
  menu.style.top = event.clientY - 150 + "px";
  // console.log(event.clientX, event.clientY);
  // 改变自定义菜单的隐藏与显示
  menu.style.display = "block";
  menu.style.zIndex = 1000;
};
const infoClickTb = (index) => {
  isDel();
  let menu = document.querySelector("#tbMenu1");
  menu.style.display = "none";
};
const cellMouseLeave = () => {
  let menu = document.querySelector("#tbMenu1");
  menu.style.display = "none";
};
const isDel = () => {
  let parm = {
    id: currentData.value.id,
  };
  ElMessageBox.confirm("确认删除", "确认删除", {
    confirmButtonText: "确认",
    cancelButtonText: "放弃",
    type: "warning",
  })
    .then(async () => {
      await meterPositionPlanRemove(parm)
        .then((res) => {
          getList();
          ElMessage({
            type: "success",
            message: "删除成功",
          });
        })
        .catch(() => {
          ElMessage({
            type: "warning",
            message: "删除失败",
          });
        });
    })
    .catch(() => {
      ElMessage({
        type: "warning",
        message: "删除失败",
      });
    });
};
</script>
<style lang="scss" scoped>
.scheme-form {
  display: flex;
  .scheme-form-item {
    width: 350px;
  }
  .tb-position {
    flex: 1;
    margin-left: 20px;
    .station-area {
      width: 100%;
      display: flex;
      flex-wrap: wrap;
      justify-content: flex-start;
      align-items: center;
      .station-area-item {
        flex: 1;
        height: 200px;
        background-color: #cacaca;
        text-align: center;
        padding-top: 30px;
        cursor: pointer;
        /* 间隙为5px */
        margin: 0 5px 5px 0;
        /* END */

        /* 这里的10px = (分布个数8-1)*间隙5px, 可以根据实际的分布个数和间隙区调整 */
        width: calc((100% - 35px) / 8);
        /* END */

        /* 加入这两个后每个item的宽度就生效了 */
        min-width: calc((100% - 35px) / 8);
        max-width: calc((100% - 35px) / 8);

        /* END */
        &:nth-child(8n) {
          /* 去除第3n个的margin-right */
          margin-right: 0;
        }

        p {
          height: 20px;
        }
        .item3 {
          height: 60px;
        }
      }
    }
  }
}
.tbMenuDiv {
  display: none;
  position: absolute;
  .tbMenuUl {
    height: auto;
    width: auto;
    font-size: 14px;
    text-align: left;
    border-radius: 3px;
    border: none;
    background-color: #c4c4c4;
    color: #fff;
    list-style: none;
    padding: 0 10px;

    li {
      width: 140px;
      height: 35px;
      line-height: 35px;
      cursor: pointer;
      border-bottom: 1px solid rgba(255, 255, 255, 0.47);

      &:hover {
        // background-color: rgb(26, 117, 158);
        color: rgb(54, 138, 175);
      }
    }
  }
}
</style>
<style lang="scss">
.el-input__wrapper {
  padding: 1px 5px !important;
}
</style>
